package com.debao.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.debao.common.constant.WechatConstants;
import com.debao.common.model.TempData;
import com.debao.common.model.WechatTemplateVo;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.utils.StringUtils;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.domain.dto.ClassBuySuccessMiniProgramTempDto;
import com.debao.system.mapper.ConfigMapper;
import com.debao.system.service.NotifyServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class NotifyServerImpl implements NotifyServer {

    /**
     * 课程下单订阅通知用户模板Id
     */
    private static final String openCardTemplateId = "nVcQGbuBC9xSIdyQMN9WVqVngJw3Tnatm-8Om5Oo7KI";


    /**
     * 微信公众号API的Service
     */
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private ConfigMapper configMapper;

    /**
     * 开通次卡的通知
     */
    @Override
    public void openTimeCardNotify(String openId, String couchGzhOpenId, String orderNo, String money,
                                   String userPhone, String coachPhone, String userName, String coachName,
                                   String cardName, String openTime) {
        Thread userNotificationThread = new Thread(() -> {
            // 短信通知-用户开通次卡
            openTimeCardNotifyByPhone(userPhone, cardName, openTime);
            // 短信通知-教练 用户开通课程次卡
            openTimeCardNotifyByPhoneCoach(coachPhone, cardName, userName);
            // 微信小程序通知-用户开通次卡
            openTimeCardNotifyByMiniProgram(openId, orderNo, cardName, coachName, money, openTime);
            // 微信公众号通知-教练 用户开通次卡
            openTimeCardNotifyByGzh(couchGzhOpenId, userName, cardName);

        });
        userNotificationThread.start();
    }

    @SneakyThrows
    private void openTimeCardNotifyByPhone(String phone, String name, String time) {
        if (StringUtils.isEmpty(phone)) {
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("className", name);
        params.put("time", time);
        classBuySuccessNotifyByPhone(phone, "SMS_472370158", params);
    }

    @SneakyThrows
    private void openTimeCardNotifyByPhoneCoach(String phone, String name, String userName) {
        if (StringUtils.isEmpty(phone)) {
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("course", name);
        params.put("name", userName);
        classBuySuccessNotifyByPhone(phone, "SMS_474635107", params);
    }

    private void openTimeCardNotifyByMiniProgram(String openId, String orderNo, String cardName, String coachName, String money, String time) {
        if (StringUtils.isEmpty(openId)) {
            return;
        }
        String token = configMapper.selectValueByKey(WechatConstants.APP_TOKEN);
        classBuySuccessNotifyByMiniProgram(new ClassBuySuccessMiniProgramTempDto()
                .setTemplateId(openCardTemplateId)
                .setOrderNo(orderNo)
                .setCourseName(cardName)
                .setCoachName(coachName)
                .setMoney(money)
                .setPayAt(time)
                .setToken(token)
                .setOpenId(openId)
        );
    }

    private void openTimeCardNotifyByGzh(String coachOpenId, String userName, String courseName) {
        if (StringUtils.isEmpty(coachOpenId)) {
            return;
        }
        classBuySuccessNotifyByGzh(userName, courseName, coachOpenId);
    }
    // 短信通知-用户购买成功
    @Override
    public void classBuySuccessNotifyByPhone(String phone, String templateCode, HashMap<String, Object> params) throws ClientException {
        AliyunSmsUtil.sendSms(phone, templateCode, JSONObject.toJSONString(params));
    }

    // 微信小程序-用户购买成功
    @Override
    public void classBuySuccessNotifyByMiniProgram(ClassBuySuccessMiniProgramTempDto dto) {
        Map<String, TempData> data = new HashMap<>();
        data.put("character_string1", new TempData(dto.getOrderNo()));
        data.put("thing3", new TempData(dto.getCourseName()));
        data.put("thing10", new TempData(dto.getCoachName()));
        data.put("amount6", new TempData(dto.getMoney()));
        data.put("time5", new TempData(dto.getPayAt()));
        cn.hutool.json.JSONObject result = WechatUtils.postTemplateData(new WechatTemplateVo()
                .setTemplateId(dto.getTemplateId())
                .setToken(dto.getToken())
                .setOpenid(dto.getOpenId())
                .setData(data).setPage("/subPackages/order/details/course_detail?orderNo=" + dto.getOrderNo()));
        log.info("微信订阅消息推送结果：{}", result);
    }

    // 微信公众号-用户购买成功通知教练排课
    @Override
    public void classBuySuccessNotifyByGzh(String userName, String courseName, String openId) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId("kxk12AWyG3PnPCKKpOY7MbhMjaHfzuvkWDSzZhrqb4M")
                // 模板跳转链接
                .miniProgram(new WxMpTemplateMessage.MiniProgram("wx0d1179c968aa1397", "subPackages/course/coach_course", false))
                .build();
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("thing1", "德宝乒乓(东湖昇光店)", "#000000"))
                .addData(new WxMpTemplateData("thing2", courseName, "#000000"))
                .addData(new WxMpTemplateData("thing4", userName, "#000000"));
        try {
            // 发送模板消息
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error("·==++--·推送微信模板信息失败·--++==·", e);
        }
    }
}
